package com.jsy.seckill.mq.listener;

import com.alibaba.fastjson.JSON;
import com.jsy.seckill.pojo.SeckillOrder;
import com.jsy.seckill.service.SeckillOrderService;
import net.bytebuddy.asm.Advice;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "${mq.pay.queue.seckillorder}")
public class PayMessageListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 监听处理mq支付回调信息
     *
     * @param msg
     */
    @RabbitHandler
    public void receive(String msg) {
        try {
            Map<String, String> resultMap = JSON.parseObject(msg, Map.class);
            if ("SUCESS".equals(resultMap.get("return_code"))) {
                String attach = resultMap.get("attach");
                Map<String, String> attachMap = JSON.parseObject(attach, Map.class);
                if ("SUCESS".equals(resultMap.get("result_code"))) {
                    //1支付成功 (先查询有没有该订单)更新redis支付状态 同步到mysql中 删除redis订单数据 删除排队标识
                    String outTradeNo = resultMap.get("out_trade_no");
                    String transactionId = resultMap.get("transaction_id");
                    String username = attachMap.get("username");
                    seckillOrderService.saveOrderInRedisToDB(outTradeNo, transactionId, username);
                } else {
                    //2.支付失败
                    //2支付失败 (先查询有没有该订单)回滚redis库存 删除redis订单 需要查看秒杀商品的time 商品id 用户名用来删除重复排队标识
                    seckillOrderService.deleteOrder(resultMap.get("out_trade_no"), attachMap.get("time"), attachMap.get("username"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
